package cn.itsource.org.service.impl;
import cn.itsource.basic.constant.PetHomeConstans;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.MD5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.service.IShopService;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper mapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    @Transactional
    public void saveSetIn(Shop shop) {
        //添加shop  这个时候没有admin_id
        mapper.saveSetIn(shop);
        Employee admin = shop.getAdmin();
        System.out.println(admin.getPassword());
        //设置盐值
        String random = StrUtils.getComplexRandomString(10);
        admin.setSalt(random);
        //设置密码
        admin.setPassword(MD5Utils.encrypByMd5(admin.getPassword()+random));
        //设置Logininfo
        //创建登录对象
        LoginInfo loginInfo = createLogininfo(admin);
        //添加logininfo
        loginInfoMapper.register(loginInfo);
        //添加logininfo对象
        admin.setLogininfo(loginInfo);
        //设置shop_id
        admin.setShop(shop);
        //添加employee
        employeeMapper.save(admin);
        //更新admin_id
        mapper.update(shop);

    }

    private LoginInfo createLogininfo(Employee admin) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(admin, loginInfo);
        loginInfo.setType(PetHomeConstans.Admin);
        return loginInfo;
    }

    @Override
    public List<Shop> getShopByState() {
        return mapper.getShopByState();
    }

    @Override
    @Transactional
    public void updateState(Long id) {
        mapper.updateState(id);
    }

    @Override
    public Shop loadByLogininfoid(Long id) {

        return mapper.loadByLogininfoid(id);
    }
}
